package com.example.demo.controller;

import cn.hutool.json.JSONUtil;
import com.example.demo.util.CommonConstants;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * (Test1)控制层
 *
 * @author wbx
 * @since 2021-05-14 11:16:12
 */
@RestController
@RequestMapping("/kafka")
public class KafkaController {
    /**
     * 服务
     */
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * kafka发送消息
     */
    @PostMapping("/sendMessage")
    public String sendMessage() {
        String message = "发送成功！";
        Map<String, String> map = new HashMap<>();
        map.put("user",getRandomJianHan(3));
        map.put("url","/wang");
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        ListenableFuture<SendResult<String, String>> send = kafkaTemplate.send(CommonConstants.KAFKA_TOPIC, JSONUtil.toJsonStr(map));
        if(send.isCancelled()) {
            message = "消息发送失败";
        }
        return message;
    }

    /**
     *  随机生成中文用户名
     * @param len 穿的高度
     * @return
     */
    public static String getRandomJianHan(int len) {
        String ret = "";
        for (int i = 0; i < len; i++) {
            String str = null;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBK"); // 转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret += str;
        }
        return ret;
    }

}
